<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

defined('IN_ADMIN') or die('Hacking Attempt!');

func::isLogin();
mysql::begin(1);

$sTable = 'payment';

$iPaymentId = (isset($_GET['id']) && is_numeric($_GET['id'])) ? $_GET['id'] : 0;

if(isset($_POST['updatePaymentButton'])){
    $iCustomerId = isset($_POST['customerId']) ? $_POST['customerId'] : 0;
    $aVals = array(
        'amount' => isset($_POST['amount']) ? func::numberFormatInput($_POST['amount']) : 0
    );
    $iIdUpdatePayment = mysql::updateSql($sTable, $aVals, 'paymentId', $iPaymentId);

    //update debit amount
    $iDebitAmount = isset($_POST['debitAmount']) ? $_POST['debitAmount'] : 0;
    $iTotal = $iDebitAmount - $aVals['amount'];
    $iIdUpdateDebit = mysql::updateSql('debit', array('amount' => $iTotal), 'customerId', $iCustomerId);

    if($iIdUpdatePayment && $iIdUpdateDebit){
        mysql::commit();
        func::redirect(func::makeUrl('payment', 'list'));
    }else
        mysql::rollBack();
} else{
    $sSql = 'SELECT * FROM payment WHERE paymentId='. $iPaymentId;
    $aResult = mysql::querySql($sSql);
    $aRow = mysql::fetchSql($aResult);

    $aDebitRow = mysql::selectDebitAmount('debit', $aRow['customerId']);
    $iTotal = $aDebitRow['amount'] + $aRow['amount'];
    $iIdUpdateDebit = mysql::updateSql('debit', array('amount' => $iTotal), 'customerId', $aRow['customerId']);
    if($iIdUpdateDebit)
        mysql::commit();
    else
        mysql::rollback();

    $sSql = 'SELECT name FROM customer WHERE customerId='. $aRow['customerId'];
    $aResult = mysql::querySql($sSql);
    $aCustomerRow = mysql::fetchSql($aResult);
}
?>
